//
//  UIButton+x.m
//  iLookForiPad
//
//  Created by baboy on 13-3-20.
//  Copyright (c) 2013年 baboy. All rights reserved.
//

#import "UIButton+x.h"
#import <objc/runtime.h>


@implementation UIButton (BKKit)

- (void) setImageLocation:(NSInteger)imageLocation{
    objc_setAssociatedObject(self, @selector(imageLocation), @(imageLocation), OBJC_ASSOCIATION_RETAIN);
    
    CGFloat innerMargin = 3.0f;
    if (self.imageLocation == UIButtonImageLocationTop) {

        CGSize imageSize = self.imageView.frame.size;
        imageSize.height = MIN(imageSize.height, self.bounds.size.height - self.titleLabel.bounds.size.height);
        
        CGSize titleSize = [self.titleLabel.text sizeWithAttributes:@{NSFontAttributeName:self.titleLabel.font}];
        CGFloat totalHeight = (imageSize.height + titleSize.height + innerMargin);
        
        self.imageEdgeInsets = UIEdgeInsetsMake(-self.titleLabel.bounds.size.height/2, self.titleLabel.bounds.size.width/2 , self.titleLabel.bounds.size.height/2, -
                                                self.titleLabel.bounds.size.width/2);
        self.titleEdgeInsets = UIEdgeInsetsMake(imageSize.height/2
                                                , -self.imageView.bounds.size.width, -imageSize.height/2,0);
    }
    if (self.imageLocation == UIButtonImageLocationRight) {
        self.imageEdgeInsets = UIEdgeInsetsMake(0, self.titleLabel.bounds.size.width, 0, -self.titleLabel.bounds.size.width);
        self.titleEdgeInsets = UIEdgeInsetsMake(0, -self.imageView.bounds.size.width, 0, self.imageView.bounds.size.width);
    }
}

- (NSInteger)imageLocation{
    return [objc_getAssociatedObject(self, @selector(imageLocation)) integerValue];
}

- (void)setLocalizedKey:(NSString *)localizedKey{
    [self setTitle:NSLocalizedString(localizedKey, @"UIButton") forState:UIControlStateNormal];
    if (self.autoResizeWidth) {
        [self sizeToFitWidth];
    }
}
- (NSString*)localizedKey{
    return nil;
}
- (void)setAutoResizeWidth:(BOOL)autoResizeWidth{
    objc_setAssociatedObject(self, @selector(autoResizeWidth), @(autoResizeWidth), OBJC_ASSOCIATION_RETAIN);
    if (autoResizeWidth) {
        [self sizeToFitWidth];
    }
}
- (BOOL)autoResizeWidth{
    return [objc_getAssociatedObject(self, @selector(autoResizeWidth)) boolValue];
}

- (void)sizeToFitWidth{
    CGRect bounds = self.bounds;
    bounds.size = [self sizeThatFits:CGSizeMake(CGFLOAT_MAX, bounds.size.height)];
    self.bounds = bounds;
}
@end



